package com.PointyShinyBurning.OCWDroid;

import java.io.InputStream;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

public class OCWSearch extends ListActivity{
	public static String TAG = "OCWSearch";
	
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.ocw_search);

	    Intent intent = getIntent();

	    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
	      String query = intent.getStringExtra(SearchManager.QUERY);
	      //do the search
	      setListAdapter(searchCourses(query));
	    }
	}
	
	private ListAdapter searchCourses(String query){
		JSONObject searchResults;
		ArrayAdapter<String> courses = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        try {	
            HttpClient httpclient = new DefaultHttpClient();
            String url = "http://www.ocwsearch.com/api/v1/search.json?q="+URLEncoder.encode(query ,"UTF-8")+"&contact="+URLEncoder.encode(getString(R.string.app_site) ,"UTF-8");
            HttpGet httpget = new HttpGet(url); 
            Log.i(TAG,"JSON req:"+url);

            HttpResponse response;

                response = httpclient.execute(httpget);
                Log.i(TAG,response.getStatusLine().toString());

                HttpEntity entity = response.getEntity();
     
                if (entity != null) {

                    InputStream instream = entity.getContent();
                    String result= RestClient.convertStreamToString(instream);
                    Log.i(TAG,result);
                    searchResults = new JSONObject(result).getJSONObject("Results");
                    Log.i(TAG,"Got past first results thingy");
                    instream.close();
                    
          		   for(Integer i=1; i< searchResults.length(); i++){
        		            String obj = searchResults.getJSONObject(i.toString()).getString("Title");
        		            courses.add(obj);
        		    }
                }


            } catch (JSONException e){
                e.printStackTrace();
                Log.i(TAG, "JSON Fail, dancing postponed:"+e.getMessage());
            }
        	catch (Exception e) {
                e.printStackTrace();
                Log.i(TAG, "Horrendous fail, no dancing:"+e.getMessage());
            }

		return courses;
	}
}
